package com.springboot.template.thread.pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Goods implements Runnable{
    //定义一个变量，用于存储用户编号
    private String name;
    //有参构造方法，初始化用户编号
    public Goods(String name) {
        this.name = name;
    }
    private static int count = 10;

    @Override
    public void run() {
        System.out.println(name + "进入了秒杀活动");
        if (count > 0) {
            synchronized (Goods.class) {
                System.out.println(name + "抢到了" + count + "号手机，秒杀成功！");
                count--;
            }
        }else {
            System.out.println(name + "秒杀失败");
        }
    }
}



public class TestGoods {
    public static void main(String[] args) {
        //创建阻塞队列对象
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue(5);
        //创建线程池
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 5, 6, TimeUnit.SECONDS, queue);
        //循环20个用户
        for (int i = 0; i < 20; i++) {
            Goods goods = new Goods("客户" + i);
            poolExecutor.submit(goods);
        }
    }
}
